
#include "StdAfx.h"
#include "NotifyManager.h"
#include "StringObj.h"
#include <tinyxml.h>

#ifdef WIN32
#pragma comment( lib, "tinyxml.lib" )
#endif

NotifyManager::NotifyManager(){
	tick_.reset( 1 );
	tick_.store_sec( 0, (int)time( 0 ) );
}

NotifyManager::~NotifyManager(){
}

bool NotifyManager::load( char* file_name, size_t current_sec ){
	if(! file_name )
		return false;

	TiXmlDocument doc( file_name );

	if( doc.LoadFile() == false ){
		int line = doc.ErrorRow();
		int col = doc.ErrorCol();

		return false;
	}

	if( doc.Error() )
		return false;
	
	TiXmlNode* node = 0;
	TiXmlElement* element = doc.RootElement();

	StringObj value;
	value = (char*)element->Value();
	if(! value.isEqualIgnLetterType("config") )
		return false;

	node = element->FirstChild("board");
	node = node->FirstChild("notify");

	StringObj idx;
	StringObj time_sec;
	StringObj contents;
	StringObj area;
	StringObj type;	

	Notify nfy;	

	for( node = node->FirstChild() ; node != 0 ; node = node->NextSibling()){
		node->ToElement();
		idx = node->FirstChild("idx")->FirstChild()->Value();			
		time_sec = node->FirstChild("time_sec")->FirstChild()->Value();			
		contents = node->FirstChild("contents")->FirstChild()->Value();
		area = node->FirstChild("area")->FirstChild()->Value();		
		type = node->FirstChild("type")->FirstChild()->Value();	

		nfy.area = area.to4ByteNumber();
		nfy.contents = contents.toCharacters();
		nfy.sec = time_sec.to4ByteNumber();
		nfy.type = type.to4ByteNumber();

		update_notify( nfy, current_sec );
	}

	return true;
}

void NotifyManager::update_notify( Notify& nfy, size_t current_sec ){
	Notify* value = notifys_.get( nfy.idx );

	if( value ){
		value->area = nfy.area;
		value->contents = nfy.contents;
		value->sec = nfy.sec;
		value->type = nfy.type;
	}
	else{
		value = new Notify();
		
		value->area = nfy.area;
		value->contents = nfy.contents;
		value->sec = nfy.sec;
		value->type = nfy.type;

		if( value->sec ){
			value->tick_saver.reset( 1 );
			value->tick_saver.store_sec( 0, current_sec );
		}

		notifys_.add( value->idx, value );
	}
}

NotifyManager::Notify* NotifyManager::get_fire_notify( size_t current_sec ){
	notifys_.resetCursor();
	Notify* value = 0;

	while(! notifys_.isEnd() ){
		value = notifys_.getCurrentValue();

		if( value->tick_saver.is_elapsed_sec( 0, value->sec, current_sec ) ){
			value->tick_saver.store_sec( 0, current_sec );
			return value;
		}

		notifys_.nextCursor();
	}

	return 0;
}
